import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import '../../function/states/user_state.dart';
import '../../function/widgets/loading_overlay.dart';
import '../../function/widgets/toast_widget.dart';
import '../../function/utils/mesh_url.dart';

/// 注册页面
class UserRegistrationScreen extends StatefulWidget {
  const UserRegistrationScreen({super.key});

  @override
  State<UserRegistrationScreen> createState() => _UserRegistrationScreenState();
}

class _UserRegistrationScreenState extends State<UserRegistrationScreen> {
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();
  final confirmPasswordController = TextEditingController();
  bool isLoading = false;

  /// 处理用户注册
  void handleUserRegistration() async {
    if (usernameController.text.isEmpty ||
        passwordController.text.isEmpty ||
        confirmPasswordController.text.isEmpty) {
      ToastWidget.showWarning('Please fill in all fields');
      return;
    }

    if (passwordController.text != confirmPasswordController.text) {
      ToastWidget.showError('Passwords do not match');
      return;
    }

    if (passwordController.text.length < 6) {
      ToastWidget.showWarning('Password must be at least 6 characters');
      return;
    }

    setState(() {
      isLoading = true;
    });
    LoadingOverlay.show(message: 'Creating account...', context: context);

    // 模拟网络延迟
    await Future.delayed(Duration(milliseconds: 2000));

    final success = UserState.performUserRegistration(
      account: usernameController.text.trim(),
      password: passwordController.text,
      userName: usernameController.text.trim(),
      signature: 'Welcome to Madagascar wildlife community! 🦎',
    );

    LoadingOverlay.hide();

    if (success) {
      ToastWidget.showSuccess('Registration successful!');
      // 自动登录
      final loginSuccess = UserState.performUserLogin(
        usernameController.text.trim(),
        passwordController.text,
      );
      if (loginSuccess) {
        // 这里可以跳转到主页面
        // Get.offAll(() => const MainPage());
      }
    } else {
      ToastWidget.showError('Username already exists');
    }

    setState(() {
      isLoading = false;
    });
  }

  @override
  void dispose() {
    usernameController.dispose();
    passwordController.dispose();
    confirmPasswordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Column(
              children: [
                // 顶部返回按钮和标题
                Row(
                  children: [
                    GestureDetector(
                      onTap: () => Get.back(),
                      child: Row(
                        children: [
                          Icon(
                            Icons.chevron_left,
                            color: Colors.white,
                            size: 26.sp,
                          ),
                          SizedBox(width: 12.w),
                          Text('Sign Up')
                              .fontSize(18.sp)
                              .textColor(Colors.white)
                              .fontWeight(FontWeight.w700),
                        ],
                      ),
                    ),
                  ],
                ),
                Spacer(),

                // Logo
                ClipRRect(
                  borderRadius: BorderRadius.circular(12.r),
                  child: Image.asset(
                    'assets/images/logo.png',
                    width: 118.w,
                    height: 118.w,
                    fit: BoxFit.cover,
                  ).boxShadow(
                    blurRadius: 10.r,
                    offset: Offset(0, 4.h),
                    color: Colors.black.withOpacity(0.1),
                  ),
                ),
                SizedBox(height: 60.h),

                // 用户名输入框
                Container(
                  height: 50.h,
                  decoration: BoxDecoration(
                    color: const Color(0x33FF8A3C),
                    borderRadius: BorderRadius.circular(20.r),
                    border: Border.all(color: Colors.white, width: 1.w),
                  ),
                  child: TextField(
                    controller: usernameController,
                    style: TextStyle(color: Colors.white, fontSize: 16.sp),
                    decoration: InputDecoration(
                      hintText: 'Username',
                      hintStyle: TextStyle(
                        color: Colors.grey[400],
                        fontSize: 16.sp,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 12.h,
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 16.h),

                // 密码输入框
                Container(
                  height: 50.h,
                  decoration: BoxDecoration(
                    color: const Color(0x33FF8A3C),
                    borderRadius: BorderRadius.circular(20.r),
                    border: Border.all(color: Colors.white, width: 1.w),
                  ),
                  child: TextField(
                    controller: passwordController,
                    obscureText: true,
                    style: TextStyle(color: Colors.white, fontSize: 16.sp),
                    decoration: InputDecoration(
                      hintText: 'Password',
                      hintStyle: TextStyle(
                        color: Colors.grey[400],
                        fontSize: 16.sp,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 12.h,
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 16.h),

                // 确认密码输入框
                Container(
                  height: 50.h,
                  decoration: BoxDecoration(
                    color: const Color(0x33FF8A3C),
                    borderRadius: BorderRadius.circular(20.r),
                    border: Border.all(color: Colors.white, width: 1.w),
                  ),
                  child: TextField(
                    controller: confirmPasswordController,
                    obscureText: true,
                    style: TextStyle(color: Colors.white, fontSize: 16.sp),
                    decoration: InputDecoration(
                      hintText: 'Confirm Password',
                      hintStyle: TextStyle(
                        color: Colors.grey[400],
                        fontSize: 16.sp,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 12.h,
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 110.h),

                // 注册按钮
                Container(
                  width: double.infinity,
                  height: 50.h,
                  decoration: BoxDecoration(
                    color: const Color(0x33FF8A3C),
                    borderRadius: BorderRadius.circular(20.r),
                    border: Border.all(color: Colors.white, width: 1.w),
                  ),
                  child: ElevatedButton(
                    onPressed: isLoading ? null : handleUserRegistration,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0x33FF8A3C),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20.r),
                      ),
                      elevation: 0,
                    ),
                    child: Text(
                      isLoading ? 'Creating...' : 'Sign Up',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),

                SizedBox(height: 40.h),

                // 底部条款
                RichText(
                  textAlign: TextAlign.center,
                  text: TextSpan(
                    style: TextStyle(color: Colors.white, fontSize: 11.sp),
                    children: [
                      TextSpan(text: 'By continuing, you agree to our '),
                      WidgetSpan(
                        child: GestureDetector(
                          onTap: () => MeshUrl.launchTerms(),
                          child: Text(
                            'Terms of Service',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 11.sp,
                              fontWeight: FontWeight.w600,
                              decoration: TextDecoration.underline,
                              decorationColor: Colors.white,
                            ),
                          ),
                        ),
                      ),
                      TextSpan(text: ' and '),
                      WidgetSpan(
                        child: GestureDetector(
                          onTap: () => MeshUrl.launchEula(),
                          child: Text(
                            'EULA',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 11.sp,
                              fontWeight: FontWeight.w600,
                              decoration: TextDecoration.underline,
                              decorationColor: Colors.white,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 40.h),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
